﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace Pavilion.DesignerTool.ViewTools
{
    /// <summary>
    /// Interaction logic for UndoRedo.xaml
    /// </summary>
    public partial class UndoRedo : UserControl
    {
        public static readonly DependencyProperty UndoRedoControllerProperty = DependencyProperty.Register("UndoRedoController", typeof(UndoRedoController), typeof(UndoRedo),
            new PropertyMetadata(new PropertyChangedCallback(UndoRedoControllerChanged)));

        public UndoRedoController UndoRedoController { get { return (UndoRedoController)GetValue(UndoRedoControllerProperty); } set { SetValue(UndoRedoControllerProperty, value); } }

        private PropertyChangedEventHandler UndoRedoControllerUpdated;

        public UndoRedo()
        {
            InitializeComponent();
            UndoRedoControllerUpdated = (object sender, PropertyChangedEventArgs e) => { RefreshButtonStatus(); };

            RefreshButtonStatus();
        }

        private void RefreshButtonStatus()
        {
            if (UndoRedoController == null)
                this.undoButton.IsEnabled = this.redoButton.IsEnabled = false;
            else
            {
                this.undoButton.IsEnabled = UndoRedoController.CanUndo;
                this.redoButton.IsEnabled = UndoRedoController.CanRedo;
            }
        }

        private void UndoButton_Click(object sender, RoutedEventArgs e) { UndoRedoController.Undo(); }

        private void RedoButton_Click(object sender, RoutedEventArgs e) { UndoRedoController.Redo(); }

        static private void UndoRedoControllerChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
        {
            UndoRedo view = (dependencyObject as UndoRedo);

            if (args.OldValue != null)
                (args.OldValue as UndoRedoController).PropertyChanged -= view.UndoRedoControllerUpdated;

            if (view.UndoRedoController != null)
                view.UndoRedoController.PropertyChanged += view.UndoRedoControllerUpdated;

            view.RefreshButtonStatus();
        }
    }
}
